package com.fh.service.cuijimanage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fh.mapper.loan.*;
import com.fh.model.Page;
import com.fh.model.loan.*;
import com.fh.util.HttpUtils;
import com.fh.util.PageData;
import com.fh.util.R;
import com.github.pagehelper.PageHelper;
import com.ybd.common.lang.StringUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/5/8/008.
 */
@Service
public class CuijimanageServiceImpl {

	private Logger logger = LoggerFactory
			.getLogger(CuijimanageServiceImpl.class);

	// 短信接口
	@Value("${url.shanlinURL}")
	private String sendMessageUrl;

	// 今日现金接口
	@Value("${url.cashURL}")
	private String cashURL;

	@Autowired
	private CallLoanInfoMapper mapper;

	@Autowired
	private CallLoanLogMapper callLoanLogMapper;

	@Autowired
	private UserContactsInfoMapper userContactsInfoMapper;

	@Autowired
	private CallLoanSysLogMapper callLoanSysLogMapper;

	@Autowired
	private CallLoanConverseInfoMapper callLoanConverseInfoMapper;

	@Autowired
	private ReducteOverdueInfoMapper reducteOverdueInfoMapper;

	@Autowired
	private SysUserMapper sysUserMapper;

	@Autowired
	private CallLoanUserInfoMapper callLoanUserInfoMapper;

	@Autowired
	private CallLoanBorrowInfoMapper callLoanBorrowInfoMapper;

	@Autowired
	private CallLoanBorrowDetailMapper callLoanBorrowDetailMapper;

	@Autowired
	private MidUserContactsInfoMapper midUserContactsInfoMapper;

	@Autowired
	private RepayRecordMapper repayRecordMapper;

	@Autowired
	private CallLoanInfoMapper callLoanInfoMapper;
	
	@Autowired
	private CallLoanOverInfoMapper callLoanOverInfoMapper;

	// 获取案件列表
	public List<PageData> anjianlistPage(Page page) throws Exception {
		R.setPageHelper(page.getPd());
		List<PageData> list = mapper.findistPage1(page);
		R.setPage(page, list);
		return list;
	}
	
	// 获取结案案件列表
	public List<PageData> caseOverlistPage(Page page) throws Exception {
		R.setPageHelper(page.getPd());
		List<PageData> list = callLoanOverInfoMapper.findMessageOverListPage(page);
		R.setPage(page, list);
		return list;
		}

	// 修改案件标记状态
	@Transactional
	public int updateCallRemarkStatus(Map<String, Object> para) {
		return mapper.updateCallRemarkStatus(para);
	}

	// 获取催收列表
	public List<CallLoanLog> findAllLogList(Map<String, Object> mao) {
		return callLoanLogMapper.findAllLogList(mao);
	}

	// 获取联系人列表
	public List<UserContactsInfo> findAllContactsInfoListByUserId(
			Map<String, Object> map) {
		List<UserContactsInfo> list = userContactsInfoMapper
				.findAllContactsInfoListByUserId(map);
		for (UserContactsInfo userContactsInfo : list) {
			userContactsInfo.setContMobile1Show(userContactsInfo
					.getContMobile1());
			userContactsInfo.setContMobile2Show(userContactsInfo
					.getContMobile2());
			userContactsInfo.setContMobile3Show(userContactsInfo
					.getContMobile3());
		}
		return list;
	}

	// 根据userid获取单个案件信息
	public CallLoanInfo findCallLoanInfoByUserId(Map<String, Object> map) {
		return mapper.findCallLoanInfoByUserId(map);
	}
	// 根据userid获取单个案件信息
	public CallLoanInfo findCallLoanOverInfoByUserId(Map<String, Object> map) {
		return callLoanOverInfoMapper.findCallLoanOverInfoByUserId(map);
	}

	/**
	 * 根据userid 和repaymentId获取借款案件详情（调接口） By yc
	 */
	public CallLoanBorrowInfo getanjianDescByUseridAndBorrowId(String userId,
			String repaymentId) {
		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("repaymentId", repaymentId);
		CallLoanBorrowInfo borrowInfo = callLoanBorrowInfoMapper
				.selectLoanBorrowInfo(map);
		return borrowInfo;
	}

	/**
	 * 获取催收人详情
	 *
	 * @param map
	 * @return
	 */
	public CallLoanUserInfo getCallLoanUserInfo(String userId) {
		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		// map.put("borrowid", borrowid);
		CallLoanUserInfo callLoanUserInfo = callLoanUserInfoMapper
				.selectUserInfo(map);
		return callLoanUserInfo;
	}

	/**
	 * 根据银行卡类型获取催收人详情
	 *
	 * @param map
	 * @return
	 */
	public CallLoanUserInfo getUserInfoByType(String userId, String bankType) {
		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("bankType", bankType);
		CallLoanUserInfo callLoanUserInfo = callLoanUserInfoMapper
				.getUserInfoByType(map);
		if (callLoanUserInfo != null && callLoanUserInfo.getMobile() != null)
			callLoanUserInfo.setMobileShow(callLoanUserInfo.getMobile());
		return callLoanUserInfo;
	}

	/**
	 * 调今日现金接口获取三个金额
	 *
	 * @param map
	 * @return map
	 */
	public Map<String, Object> getAmountDesc(String userId, String repayId) {
		Map<String, String> paramMap = new HashMap<>();
		paramMap.put("userId", userId);
		paramMap.put("repaymentId", repayId);
		logger.info("调今日现金接口getAmountDesc接口Url==>{}", cashURL);
		String result = HttpUtils.sendPost(cashURL
				+ "v1/api/borrow/search/getAmountDesc", paramMap);
		logger.info("调今日现金接口getAmountDesc接口返回值==>{}", result);
		Map<String, Object> mao = new HashMap<>();
		if (!StringUtils.isEmpty(result)) {
			JSONObject jsonObject = JSON.parseObject(result);
			if (Integer.valueOf(jsonObject.get("code").toString()) == 200) {
				mao = (Map<String, Object>) jsonObject.get("model");
			}
		}
		return mao;
	}

	// 根据Id获取联系人部分字段供短信界面使用
	public Map<String, Object> findContactsInfoById(Map<String, Object> map) {
		return userContactsInfoMapper.findContactsInfoById(map);
	}

	// 催记消息未读数
	public int msgCount(Map<String, Object> map) {
		return callLoanSysLogMapper.msgCount(map);
	}

	// 催记消息列表
	// @Transactional(readOnly = true)
	public Page cuijiPage(Page page) {
		int currentPage = page.getCurrentPage();
		int pageSize = page.getShowCount();
		com.github.pagehelper.Page p = PageHelper.startPage(currentPage,
				pageSize);
		List<PageData> list = callLoanSysLogMapper.cuijiListPage(page);
		page.setTotalResult(p.getTotal());
		page.setTotalPage(p.getPages());
		page.setPageList(list);
		return page;
	}

	// 催记消息标记已读
	@Transactional
	public int updateWeiduStatus(Map<String, Object> map) {
		return callLoanSysLogMapper.updateWeiduStatus(map);
	}

	// 催记消息页面删除
	@Transactional
	public int cuijiMsgDelete(Map<String, Object> map) {
		return callLoanSysLogMapper.cuijiMsgDelete(map);
	}

	// 催记消息未读列表
	public List<PageData> cuijiWeidulistPage(Page page) {
		return callLoanSysLogMapper.cuijiWeidulistPage(page);
	}

	// 插入催记消息
	@Transactional
	public int insertCuijiMsg(CallLoanSysLog callLoanSysLog) {
		return callLoanSysLogMapper.insertCuijiMsg(callLoanSysLog);
	}

	/**
	 * 获取还款详情 By yc
	 */
	public CallLoanBorrowDetail getHuankuanDescByUseridAndBorrowId(
			String userId, String repaymentId) {
		CallLoanBorrowDetail detail = callLoanBorrowDetailMapper
				.selectReturnDetail(userId, repaymentId);
		return detail;
	}

	// 即 时发送短信
	public String sendMessage(Map<String, String> param) { // 106.14.193.214:8080/sms/v1/api/sms/send
		logger.info("短信url==>{}", sendMessageUrl + "v1/api/sms/send");
		logger.info("短信入参==>{}", JSON.toJSON(param));
		String ret = HttpUtils.sendPost(sendMessageUrl + "v1/api/sms/send",
				param);
		logger.info("短信回掉结果==》{}", ret);
		return ret;
	}

	// 删除联系人
	@Transactional
	public int deluserContactsInfoById(String id) {
		Map<String, Object> mao = new HashMap<>();
		mao.put("isdel", 1);
		// int id1 = Integer.valueOf(id);
		mao.put("id", id);
		mao.put("updateTime", new Date());
		int a = userContactsInfoMapper.updateById(mao);
		return a;
	}

	// 插入短信通话记录
	@Transactional
	public int insertCallLoanConverseInfo(
			CallLoanConverseInfo callLoanConverseInfo) {
		return callLoanConverseInfoMapper.insert(callLoanConverseInfo);
	}

	// 短信发送成功，修改短信通话表的状态
	@Transactional
	public int updateCallLoanConverseInfo(String id) {
		Map<String, Object> mao = new HashMap<>();
		mao.put("status", 2);
		mao.put("id", id);
		mao.put("updateTime", new Date());
		int a = callLoanConverseInfoMapper.updateCallLoanConverseInfo(mao);
		return a;
	}

	// 获取罚息信息
	public Map<String, Object> reduInfoToanjianDesc(String callLoanNid) {
		Map<String, Object> mao = new HashMap<>();
		mao.put("callLoanNid", callLoanNid);
		return reducteOverdueInfoMapper.reduInfoToanjianDesc(mao);
	}

	// 通过接口获取原有联系人信息
	public List<MidUserContactsInfo> getOldContactsUserInfo(String userId) {
		Map<String, Object> parameters = new HashMap<>();
		parameters.put("userId", userId);
		List<Map<String, Object>> mapslist = new ArrayList<>();
		List<MidUserContactsInfo> midUserContactsInfo = midUserContactsInfoMapper
				.selectUserContactsInfo(parameters);
		return midUserContactsInfo;
	}

	// 原有联系人信息入库
	@Transactional
	public int saveOldContactsUserInfo(
			List<MidUserContactsInfo> midUserContactsInfo,
			Map<String, Object> mappra) {
		int a = 0;
		List<UserContactsInfo> batchInsertList = new ArrayList<>();
		for (MidUserContactsInfo mao : midUserContactsInfo) {
			UserContactsInfo userContactsInfo = new UserContactsInfo();
			// userContactsInfo.setId(Integer.valueOf(mao.get("id").toString()));
			userContactsInfo.setUserId(Integer.valueOf(mao.getUserId()
					.toString()));
			userContactsInfo.setOldId(Integer.valueOf(mao.getId().toString()));
			userContactsInfo.setContType(mao.getContType().toString());
			userContactsInfo.setContShip(mao.getContShip().toString());
			userContactsInfo.setContStatus(mao.getContStatus().toString());
			userContactsInfo.setContSource("0");
			userContactsInfo.setContUserName(mao.getContUserName().toString());
			userContactsInfo.setContMobile1(mao.getContMobile().toString());
			userContactsInfo.setContAddr(mao.getContAddr().toString());
			userContactsInfo.setIsdelete(0);
			userContactsInfo.setCreateTime(new Date());
			userContactsInfo.setUpdateTime(new Date());
			Map<String, Object> mapparam = new HashMap<>();
			mapparam.put("oldId", userContactsInfo.getOldId());
			Map<String, Object> map = userContactsInfoMapper
					.findContactsInfoByOldId(mapparam);
			if (map == null) {// 该原有联系人没有在落地，放入批量插入集合
				batchInsertList.add(userContactsInfo);
			}
		}
		if (batchInsertList.size() > 0) {
			a = insertUserContactsInfo(batchInsertList);
		}
		return a;
	}

	/**
	 * 下期调用这个方法，处理并发问题 addby 赵荣磊
	 *
	 * @param mapparam
	 * @param userContactsInfo
	 * @return
	 */
	@Transactional
	public int insertUserContactsInfo(List<UserContactsInfo> batchInsertList) {
		int a = 0;
		int b = 0;
		boolean isBatchInsert = true;
		try {
			logger.info("要批量插入的list的size==>{}", batchInsertList.size());
			a = userContactsInfoMapper.batchInsert(batchInsertList);
			logger.info("批量插入原有联系人返回值a==>{}", a);
		} catch (Exception e) {
			isBatchInsert = false;
			logger.error("批量插入原有联系人异常==》{}", e.getMessage());
		}
		if (!isBatchInsert) {
			logger.info("批量插入失败，走单个插入模式");
			for (UserContactsInfo userContactsInfo : batchInsertList) {
				Map<String, Object> mapparam = new HashMap<>();
				mapparam.put("oldId", userContactsInfo.getOldId());
				Map<String, Object> map = userContactsInfoMapper
						.findContactsInfoByOldId(mapparam);
				if (map == null) {
					synchronized (this) {
						map = userContactsInfoMapper
								.findContactsInfoByOldId(mapparam);
						if (map == null) {
							try {
								b = userContactsInfoMapper
										.insert(userContactsInfo);
								logger.info("单个插入返回值及userContactsInfo==>{}", b
										+ "---" + JSON.toJSON(userContactsInfo));
							} catch (Exception e) {
								logger.error("单条插入失败==>{}", e.getMessage());
							}
							a += b;
						}
					}
				}
			}
			logger.info("单条插入一共执行了--{}--条", a);
		}
		return a;
	}

	// 获取催收元用户名
	public Map<String, Object> findUserByUserId(String userId) {
		Map<String, Object> mao = new HashMap<>();
		mao.put("userId", userId);
		return sysUserMapper.findUserByUserId(mao);
	}

	// 添加催收记录
	@Transactional
	public int addRecord(CallLoanLog callLoanLog) {
		   CallLoanInfo callLoanInfo = new CallLoanInfo();
		   callLoanInfo.setCallLoanNid(callLoanLog.getCallLoanNid());
		   //催收方式
		   callLoanInfo.setCallType(callLoanLog.getCallType());
		   callLoanInfo.setCallResult(callLoanLog.getCallResult());//催收结果
		   callLoanInfo.setPromiseRepaymentDay(callLoanLog.getPromiseRepaymentDay());//承诺还款时间
		   callLoanInfo.setUpdateTime(new Date());
		   callLoanInfo.setLastCallTime(new Date());

		   CallLoanOverInfo callLoanOverInfo=callLoanOverInfoMapper.selectCaseOverByCallLoanNid(callLoanLog.getCallLoanNid());
		   if(callLoanOverInfo!=null){
		   	  int k=0;
			  k = updateCallCaseByCalllaonNid(callLoanInfo);
			   if (k != 1) {
				      logger.info("--------------更新已结案案件信息表催收记录失败----------------k={}",k);
				   }else{
				      logger.info("--------------更新已结案案件信息表催收记录成功----------------k={}",k);
			   }
			   int j=0;
			   j = updateCallLoanInfoCallResult(callLoanInfo);//更新催收案件详情表中的催收结果和催收方式
			   if (j != 1) {
				   logger.info("--------------对已结案案件更新主表中的已结案案件的催收结果和催收方式失败----------------j={}",j);
			   }else{
				   logger.info("--------------对已结案案件更新主表中的已结案案件的催收结果和催收方式成功----------------j={}",j);
			   }
		   }else{
			     int j=0;
			     j = updateCallLoanInfoCallResult(callLoanInfo);//更新催收案件详情表中的催收结果和催收方式
			     if (j != 1) {
				   logger.info("--------------对未结案案件更新主表中的催收结果和催收方式失败----------------j={}",j);
			   }else{
					 logger.info("--------------对未结案案件更新主表中的催收结果和催收方式成功----------------j={}",j);
				 }
		   }
		  int i = callLoanLogMapper.insert(callLoanLog);
		   return i;
		}
	//添加催收记录 同时更新callloaninfo案件主表的三个字段
	public int updateCallLoanInfoCallResult(CallLoanInfo callLoanInfo){
		return mapper.updateCallLoanInfoCallResult(callLoanInfo);
	}

	//添加催收记录 同时更新call_loan_over_info的三个字段
	public int updateCallCaseByCalllaonNid(CallLoanInfo callLoanInfo){
		return  callLoanOverInfoMapper.updateCaseOverBycallloannid(callLoanInfo);
	}

	// 获取催收记录的时间最大值
	public Map<String, Object> findMaxCreateTimeLogList(Map<String, Object> mao) {
		return callLoanLogMapper.findMaxCreateTimeLogList(mao);
	}

	// 获取所有状态为0，1的案件列表
	public List<CallLoanInfo> findAllListdaiandzhong() {
		return mapper.findAllListdaiandzhong();
	}

	// 获取短信通话列表
	public List<CallLoanConverseInfo> findAllConverseInfoListByCallLoanId(
			Map<String, Object> mao) {
		return callLoanConverseInfoMapper
				.findAllConverseInfoListByCallLoanId(mao);
	}

	// 获取借款人姓名
	public CallLoanInfo faxijianmianApplyById(String callLoanNid) {
		return mapper.faxijianmianApplyById(callLoanNid);
	}

	public List<RepayRecord> findRepayRecordList(Map<String, Object> mao) {
		return repayRecordMapper.findRepayRecordList(mao);
	}

	// 处理mq里msg的逻辑
	@Transactional
	public void doMqMessage(String msg) {
		logger.info("接收到的mq的msg为==>{}", msg);
		JSONObject jsonObject = JSON.parseObject(msg);
		String userId = jsonObject.getString("userId");// 用户id
		String borrowNid = jsonObject.getString("borrowNid");// 借款标号
		String repaymentId = jsonObject.getString("repaymentId");// 还款订单号
		int period = Integer.valueOf(jsonObject.get("period") + "");// 期数
		Map<String, Object> mao = (Map<String, Object>) jsonObject.get("data");
		CallLoanBorrowDetail callLoanBorrowDetail = new CallLoanBorrowDetail();
		RepayRecord repayRecord = new RepayRecord();
		CallLoanBorrowInfo callLoanBorrowInfo = new CallLoanBorrowInfo();
        CallLoanInfo info = new CallLoanInfo();
        
        int sourceType = (int) mao.get("sourceType");//来源方式 1 跑批 2 实时
        		//======================设置主表信息============================
        		info.setRepaymentId(repaymentId);//设置还款订单号
        		info.setActualRecoverAmount(new BigDecimal(String.valueOf(mao.get("acountYet"))));//设置主表已还金额 =已还金额
        		info.setNotReturnAmount(new BigDecimal(String.valueOf(mao.get("acountRemain"))));//设置主表未还金额
        		info.setOverdueAmount(new BigDecimal(String.valueOf(mao.get("acountRemain"))));//设置逾期总金额 = 未还金额
        		info.setOverdueCaptial(new BigDecimal(String.valueOf(mao.get("capitalRemain"))));//设置逾期本金 = 未还本金
        		info.setOverdueInterest(new BigDecimal(String.valueOf(mao.get("interestRemain"))));//设置逾期利息 = 未还利息
        		info.setOverdueManFee(new BigDecimal(String.valueOf(mao.get("remainBorrowFee"))));//设置逾期管理费 = 未还管理费
        		info.setOverdueSerFee(new BigDecimal(String.valueOf(mao.get("remainServiceFee"))));//设置逾期平台服务费 = 未还平台服务费 
        		info.setOverdueFee(new BigDecimal(String.valueOf(mao.get("remainOverdueFee"))));//设置未还罚息
        		info.setUserReduOverdueFee(new BigDecimal(String.valueOf(mao.get("mitigatePenaltyAmount"))));//设置已使用的罚息减免金额
        		info.setReceveFee(new BigDecimal(String.valueOf(mao.get("receveOverdueFee"))));//设置已还罚息
        		info.setRemainAccount(info.getOverdueAmount().subtract(new BigDecimal(String.valueOf(mao.get("remainOverdueFee")))));//累计未还金额 = 未还金额 - 未还罚息
        		//======================设置主表信息============================
                int repayType = (int) mao.get("repayType");//还款类型 1 为全部还清 0为部分还款
                repayRecord.setBorrowNid(borrowNid);
                repayRecord.setPeriod(period);
                repayRecord.setRepaymentId(repaymentId);
                repayRecord.setUserId(userId);
                //获取当前时间
                String current = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                Timestamp time = Timestamp.valueOf(current);
                  repayRecord.setUpdateTime(time);
                 repayRecord.setCreateTime(time);
                repayRecord.setRepayType(repayType);
                repayRecord.setIsAuto(sourceType + "");
                repayRecord.setRecoverTime((Long) mao.get("recoverTime"));//还款时间 为时间戳 repay_record_log
                repayRecord.setPartAcountyet(new BigDecimal(mao.get("partAcountYet") + ""));//本次还款金额 repay_record_log
                repayRecord.setAcountYet(new BigDecimal(mao.get("acountYet") + ""));//已还款金额 repay_record_log

                callLoanBorrowDetail.setOverdueFee(new BigDecimal(mao.get("overdueFee") + ""));//总罚息 call_loan_borrow_detail
                callLoanBorrowDetail.setAcountYet(new BigDecimal(mao.get("acountYet") + ""));//已还总额 call_loan_borrow_detail
                CallLoanBorrowInfo  callLoanBorrowInfo1 = this.getanjianDescByUseridAndBorrowId(userId, repaymentId);
            if(callLoanBorrowInfo1!=null) {
                if (callLoanBorrowInfo1.getAcountWait().compareTo(callLoanBorrowDetail.getAcountYet()) == 1) {
                    repayRecord.setHexiaoAcount(repayRecord.getPartAcountyet());
                }else if(callLoanBorrowInfo1.getAcountWait().compareTo(callLoanBorrowDetail.getAcountYet()) == 0){
                    repayRecord.setHexiaoAcount(repayRecord.getPartAcountyet());
                }else {
                    repayRecord.setHexiaoAcount(callLoanBorrowInfo1.getAcountWait());
                }
            }else{
                repayRecord.setHexiaoAcount(repayRecord.getPartAcountyet());
            }
            /**
          	  * 此处增加如果今日现金跑批完成，催收系统还未跑批，中间用户进行还款的行为，会造成催收系统查不到改用户的还款信息。
          	  * 在数据库新增repay_record_log表记录两个系统对接跑批时产生的遗漏数据。
          	 */
           CallLoanInfoDto callLoanInfoDto = new CallLoanInfoDto();
           callLoanInfoDto.setRepaymentId(repaymentId);
           CallLoanInfoDto callLoanInfo = callLoanInfoMapper.fetchByRepaymentId(callLoanInfoDto);
           if (callLoanInfo ==null) {
               logger.info("·············repay_record_log表已经记录该条遗漏的逾期案件====》》repaymentId··················="+repaymentId);
               repayRecord.setIsMiss("Y");//repay_record_log记录跑批遗漏数据
           }
                callLoanBorrowDetail.setReceveCaptialYes(new BigDecimal(mao.get("receveCaptialYes") + ""));//以还本金 call_loan_borrow_detail
                callLoanBorrowDetail.setReceveInterestYes(new BigDecimal(mao.get("receveInterestYes") + ""));//以还利息 call_loan_borrow_detail
                callLoanBorrowDetail.setReceveServiceFee(new BigDecimal(mao.get("receveServiceFee") + ""));//以还服务费 call_loan_borrow_detail
                callLoanBorrowDetail.setReceveBorrowFee(new BigDecimal(mao.get("receveBorrowFee") + ""));//以还管理费 call_loan_borrow_detail
                callLoanBorrowDetail.setReceveOverdueFee(new BigDecimal(mao.get("receveOverdueFee") + ""));//以还罚息 call_loan_borrow_detail
                callLoanBorrowDetail.setBorrowNid(borrowNid);
                callLoanBorrowDetail.setRepaymentId(repaymentId);
                callLoanBorrowDetail.setUpdateTime(new Date());

                callLoanBorrowInfo.setAcountRemain(new BigDecimal(mao.get("acountRemain") + ""));//未还总额 call_loan_borrow_info
                callLoanBorrowInfo.setRemainServiceFee(new BigDecimal(mao.get("remainServiceFee") + ""));//未还平台服务费 call_loan_borrow_info
                callLoanBorrowInfo.setRemainBorrowFee(new BigDecimal(mao.get("remainBorrowFee") + ""));//未还借款管理费 call_loan_borrow_info
                callLoanBorrowInfo.setRemainOverdueFee(new BigDecimal(mao.get("remainOverdueFee") + ""));//未还罚息 call_loan_borrow_info
                callLoanBorrowInfo.setRepaymentId(repaymentId);
                callLoanBorrowInfo.setBorrowNid(borrowNid);
                callLoanBorrowInfo.setUpdateTime(new Date());

               /* String mitigatePenaltyAmount = mao.get("mitigatePenaltyAmount") + "";//以用罚息减免金额
                BigDecimal capitalRemain = (BigDecimal) mao.get("capitalRemain");//未还本金
                BigDecimal interestRemain = (BigDecimal) mao.get("interestRemain");//未还利息*/

               //加入下面两个字段
		        repayRecord.setUserReduOverdueFee(new BigDecimal(mao.get("mitigatePenaltyAmount") + ""));//以用罚息减免金额
                repayRecord.setCapitalRemain(new BigDecimal(mao.get("capitalRemain") + ""));
                repayRecord.setInterestRemain(new BigDecimal(mao.get("interestRemain") + ""));

               try{
                 int a =  repayRecordMapper.insert(repayRecord);
                 logger.info("repay_record_log批量更新条数==>{}",a);
              }catch (Exception e){
                 logger.error("repay_record_log表insert sql出错==>{}",e.getMessage());
              }

                   int b = callLoanBorrowDetailMapper.updateCallLoanBorrowDetail(callLoanBorrowDetail);
                   int c = callLoanBorrowInfoMapper.updateCallLoanBorrowInfo(callLoanBorrowInfo);
                    logger.info("call_loan_borrow_detail批量更新条数==>{}",b);
                    logger.info("call_loan_borrow_info批量更新条数==>{}",c);
                   //更改主表中的数据
                   try {
                	   if (callLoanInfo != null) {
                		   //info.setVersion(callLoanInfo.getVersion());//设置版本号
                		   mapper.updateByMoney(info);
                	   }
                   } catch (Exception e) {
                	   logger.error("更新主表数据异常:还款订单号:" + info.getRepaymentId(),e);
                   }
    }
}
